import React, { useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useImageCollection, ImageCollectionItem } from '../../hooks/useImageCollection';
import CollectionHeader from './components/CollectionHeader';
import ImageCollectionGrid from './components/ImageCollectionGrid';

/**
 * 图片生成收藏页面
 */
const GenerateImage: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { data, loading, loadingMore, error, sortBy, hasMore, updateSortBy, loadMore } = useImageCollection();
  const headerRef = useRef<HTMLDivElement>(null);

  /**
   * 处理收藏项点击事件
   */
  const handleItemClick = (item: ImageCollectionItem) => {
    // console.log(`🔄 ${t('collection.title')}:`, item);
    // console.log('🔄 Navigating to:', `/collection?username=${encodeURIComponent(item.username)}`);

    // 获取AI角色ID - 优先使用item.id，如果没有则使用username
    const aiPersonId = item.ai_person_id;

    // console.log('🔍 AI Person ID:', {
    //   itemId: item.ai_person_id,
    //   username: item.username,
    //   finalAiPersonId: aiPersonId
    // });

    // 跳转到collection页面，URL中只显示username，其他信息通过state传递
    navigate(`/collection?username=${encodeURIComponent(item.username)}`, {
      state: {
        avatar: item.avatar,
        id: aiPersonId, // 传递AI角色ID
        username: item.username,
        images: item.Images,
        created_at: item.created_at
      }
    });

  };

  return (
    <div className="min-h-screen bg-[rgb(19,19,19)]">
      {/* 头部：标题和排序 - 当滚动到顶部时会自动吸顶 */}
      <div ref={headerRef} className="sticky top-0 z-10">
        <CollectionHeader
          sortBy={sortBy}
          onSortChange={updateSortBy}
        />
      </div>

      {/* 内容区域：图片收藏网格 */}
      <div className='w-full mt-6 px-4 sm:px-6 md:px-8 lg:w-[90%] lg:mx-auto lg:px-0'>
        <ImageCollectionGrid
          data={data}
          loading={loading}
          loadingMore={loadingMore}
          error={error}
          hasMore={hasMore}
          onItemClick={handleItemClick}
          onLoadMore={loadMore}
        />
      </div>

    </div>
  );
};

export default GenerateImage;
